package com.sense.lib.webview;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.sense.lib.webview.callback.OnUrlListener;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.HashMap;

/**
 * <br> ClassName:   SenseWebViewClient.java
 * <br> Description:
 * <br> Author:      lionszhang
 * <br> Date:        2022/1/27
 */
public class SenseWebViewClient extends WebViewClient {
    private SenseWebView webView;
    private OnUrlListener mOnUrlListener;
    private String TAG="SenseWebViewClient";
    /**
     * url加载状态Map
     * 用于解决Android 4.4版本中，onPageFinished() 被调用2次的问题
     */
    private HashMap<String, Boolean> urlStateMap;

    public SenseWebViewClient(SenseWebView webView) {
        this.webView = webView;
        urlStateMap = new HashMap<>();
    }

    @Override
    public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
        //handler.cancel(); 默认的处理方式，WebView变成空白页
        //接受证书
//        handler.proceed();
        //handleMessage(Message msg); 其他处理
        Log.e(TAG, "onReceivedSslError>>");
        AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
        builder.setMessage("ssl_fail");
        builder.setPositiveButton("continue", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                handler.proceed();
            }
        });
        builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                handler.cancel();
            }
        });
        builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                    handler.cancel();
                    dialog.dismiss();
                    return true;
                }
                return false;
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    public void setOnUrlListener(OnUrlListener mUrlListener) {
        this.mOnUrlListener = mUrlListener;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        try {
            url = URLDecoder.decode(url, "UTF-8");
            if (handlerUrl(view, url)) {
                return true;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return super.shouldOverrideUrlLoading(view, url);
    }

    private boolean handlerUrl(WebView view, String url) {
        Log.e(TAG, "url="+url);
        /*if (url.startsWith("intent://discordapp")) {
            Intent intent;
            try {
                intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
            } catch (URISyntaxException e) {
                Log.e(TAG, "URISyntaxException: " + e.getLocalizedMessage());
                return false;
            }
            intent.setComponent(null);
            try {
                view.getContext().startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Log.e(TAG, "ActivityNotFoundException: " + e.getLocalizedMessage());
                return false;
            }
            return true;
        }*/
        return false;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);

//        if (urlStateMap != null) {
//            urlStateMap.put(url, false);
//        }
        if (mOnUrlListener != null) {
            mOnUrlListener.onPageStarted(webView, url,favicon);
        }
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
//        if (urlStateMap != null && urlStateMap.containsKey(url) && !urlStateMap.get(url)) {
//            urlStateMap.put(url, true);
//            if (mOnUrlListener != null) {
//                mOnUrlListener.onPageFinished(webView, url);
//            }
//        }
        if (mOnUrlListener != null) {
            mOnUrlListener.onPageFinished(webView, url);
        }
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        if (mOnUrlListener != null) {
            mOnUrlListener.onReceivedError(view, errorCode, description, failingUrl);
        }
        Log.e(TAG, "onReceivedError>>");
    }

    public void destroy() {
        if (urlStateMap != null) {
            urlStateMap.clear();
            urlStateMap = null;
        }
    }

}